package com.juyu.miliao.authentication.controller;

import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.DataValidateException;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.exception.NoPermissionException;
import com.juyu.miliao.common.msg.CommonErrorMsgs;
import com.juyu.miliao.common.msg.DetailErrorMsg;
import com.juyu.miliao.common.msg.ErrorMsg;
import com.juyu.miliao.common.security.exception.WrongVerificationCodeException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

@RestControllerAdvice
public class ExceptionHandlers implements CommonErrorMsgs {

	@ExceptionHandler({ BindException.class, IllegalParamException.class })
	public ResponseEntity<ErrorMsg> handleBindException(Exception ex) throws Exception {
		ErrorMsg errorMsg = null;
		if(ex instanceof BindException){
			BindException bindException = (BindException)ex;
			Map<String, String> errorFieldsMap = bindException.getFieldErrors().stream().collect(toMap(FieldError::getField, FieldError::toString));
			errorMsg = new DetailErrorMsg(ILLEGAL_PARAM, errorFieldsMap);
		}else if(ex instanceof IllegalParamException){
			IllegalParamException illegalParamException = (IllegalParamException)ex;
			errorMsg = new DetailErrorMsg(ILLEGAL_PARAM, illegalParamException.getMessage(), illegalParamException.getDetail());
		}else
			throw ex;
		return new ResponseEntity<ErrorMsg>(errorMsg, errorMsg.getStatus());
	}
	
	@ExceptionHandler({ NoPermissionException.class, AccessDeniedException.class })
	public ResponseEntity<ErrorMsg> handleAccessDeniedException(NoPermissionException ex) throws Exception {
		return new ResponseEntity<ErrorMsg>(NO_PERMISSION, NO_PERMISSION.getStatus());
	}
	/**
	 * 验证码错误
	 */
	@ExceptionHandler({ WrongVerificationCodeException.class })
	public ResponseEntity<?> handleWrongVerificationCodeException(WrongVerificationCodeException ex)
			throws Exception {
		return new ResponseEntity<ErrorMsg>(VERIFICATION_CODE, VERIFICATION_CODE.getStatus());
	}

	@ExceptionHandler({DataValidateException.class})
	public ResponseEntity<?> handleDataValidateException(DataValidateException ex)
			throws Exception {
		return new ResponseEntity<>(new ErrorMsg(HttpStatus.BAD_REQUEST, "20000", ex.getMessage()), HttpStatus.BAD_REQUEST);
	}

	@ExceptionHandler({ConsumeRuntimeException.class})
	public ResponseEntity<?> handleConsumeRuntimeExceptionException(ConsumeRuntimeException ex)
			throws Exception {
		return new ResponseEntity<>(ex.getErrorMsg(), ex.getErrorMsg().getStatus());
	}
	

}
